/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.services.servlets;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.ProfileItem;
import com.phonebooksharing.dto.ReturnItem;
import com.phonebooksharing.dto.friend.GroupItem;
import com.phonebooksharing.dto.gallery.ImageGalleryItem;
import com.phonebooksharing.dto.gallery.VideoGalleryItem;
import com.phonebooksharing.dto.gallery.WishlistItem;
import com.phonebooksharing.services.ejb3.facade.ProfileFacade;
import com.phonebooksharing.services.ejb3.utils.IConstants;

/**
 * Servlet implementation class PerfilServlet
 */
public class ProfileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @EJB
    private ProfileFacade profileFacade;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProfileServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        response.setContentType("text/html");
        pw.print("<html><head/><body><h1>Welcome to Phonebook Sharing Services!</h1><br/><h3>You should be posting here!</h3></body></html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @SuppressWarnings("unchecked")
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        final String action = request.getParameter("ac");

        try {
            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            if ("v".equalsIgnoreCase(action)) {

                validate((ProfileItem) ois.readObject(), response);

            } else if ("l".equalsIgnoreCase(action)) {

                sendForgotMail(response);

            } else if ("a".equalsIgnoreCase(action)) {// add
                final String what = request.getParameter("q");
                if ("c".equalsIgnoreCase(what)) {// contacts/people

                    addContacts((GenericTransferDTO) ois.readObject(), response);

                } else if ("p".equalsIgnoreCase(what)) {// phones

                    addPhones((GenericTransferDTO) ois.readObject(), response);

                } else if ("cm".equalsIgnoreCase(what)) {// contact methods

                    addContactMethods((GenericTransferDTO) ois.readObject(), response);

                } else if ("g".equalsIgnoreCase(what)) {// groups

                    addGroups((GenericTransferDTO) ois.readObject(), response);

                } else if ("gm".equalsIgnoreCase(what)) {// groups members
                    addGroupsMembers((GenericTransferDTO) ois.readObject(), response);
                }
            } else if ("d".equalsIgnoreCase(action)) {// done sending contents
                profileFacade.scheduleAccountActivation((GenericTransferDTO) ois.readObject());

                ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                oos.writeObject(new ReturnItem(true));

            } else if ("ch".equalsIgnoreCase(action)) {

            } else if ("ms".equalsIgnoreCase(action)) {// manage sharing
                final String what = request.getParameter("q");
                if ("sig".equalsIgnoreCase(what)) {// sharing image gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.startSharingImage((ArrayList<ImageGalleryItem>) ois.readObject()));

                } else if ("nsig".equalsIgnoreCase(what)) {// stop sharing image
                                                           // gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.stopSharingImage((ArrayList<ImageGalleryItem>) ois.readObject()));
                } else if ("aig".equalsIgnoreCase(what)) {// add to image
                                                          // gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    GenericTransferDTO gt = (GenericTransferDTO) ois.readObject();
                    ArrayList<ImageGalleryItem> list = (ArrayList<ImageGalleryItem>) gt.items2;
                    oos.writeObject(profileFacade.addImagesToGallery(gt.authItem, list));

                } else if ("svg".equalsIgnoreCase(what)) {// sharing video
                                                          // gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.startSharingVideo((ArrayList<VideoGalleryItem>) ois.readObject()));
                } else if ("nsvg".equalsIgnoreCase(what)) {// stop sharing video
                                                           // gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.stopSharingVideo((ArrayList<VideoGalleryItem>) ois.readObject()));
                } else if ("avg".equalsIgnoreCase(what)) {// add to video
                                                          // gallery
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    GenericTransferDTO gt = (GenericTransferDTO) ois.readObject();
                    ArrayList<VideoGalleryItem> list = (ArrayList<VideoGalleryItem>) gt.items2;
                    oos.writeObject(profileFacade.addVideosToGallery(gt.authItem, list));
                } else if ("swl".equalsIgnoreCase(what)) {// sharing wish list
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.startSharingWishlist((ArrayList<WishlistItem>) ois.readObject()));
                } else if ("nswl".equalsIgnoreCase(what)) {// stop sharing wish
                                                           // list
                    ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
                    oos.writeObject(profileFacade.stopSharingWishlist((ArrayList<WishlistItem>) ois.readObject()));
                }
            } else if ("e".equalsIgnoreCase(action)) {

            } else if ("upr".equalsIgnoreCase(action)) { // update privacy
                ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());

                GenericTransferDTO gt = (GenericTransferDTO) ois.readObject();
                ArrayList<GroupItem> list = (ArrayList<GroupItem>) gt.items2;
                oos.writeObject(profileFacade.updatePrivacy(gt.authItem, list));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendForgotMail(HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        ReturnItem ri = new ReturnItem(true);
        // ri.setErrorCode(ProfileItem.PROFILE_EXISTS);
        // ri.setOK(true);
        oos.writeObject(ri);
    }

    private void validate(ProfileItem pi, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.validate(pi));
    }

    private void addContacts(GenericTransferDTO gt, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.addAsyncProcessor(gt, IConstants.ASSYNC_TYPE_CONTACTS));
    }

    private void addGroups(GenericTransferDTO gt, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.addAsyncProcessor(gt, IConstants.ASSYNC_TYPE_GROUPS));
    }

    private void addGroupsMembers(GenericTransferDTO gt, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.addAsyncProcessor(gt, IConstants.ASSYNC_TYPE_GROUP_MEMBERS));
    }

    private void addPhones(GenericTransferDTO gt, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.addAsyncProcessor(gt, IConstants.ASSYNC_TYPE_PHONES));
    }

    private void addContactMethods(GenericTransferDTO gt, HttpServletResponse response) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(profileFacade.addAsyncProcessor(gt, IConstants.ASSYNC_TYPE_CONTACT_METHODS));
    }
}
